<template>
	<view class="container">
		<view class="header">
			<view class="header-title">
<!--				<view class="header-icon">-->
<!--          <image :src="ORDER_STATUS_ICON[order.status]"></image>-->
<!--				</view>-->
				<view class="header-status">
					<text>{{ ORDER_STATUS_TEXT[order.status] }}</text>
				</view>
			</view>
			<view class="header-content" v-if="order.status === ORDER_STATUS.PENDING">
				<text>{{ expreTime }}分钟后订单关闭，请及时付款哦</text>
			</view>
			<view class="header-empty"></view>
		</view>
		<view class="content">
			<!-- 地址信息 -->
			<view class="address">
				<view class="address-left">
					<image src="/static/icon/address.png"></image>
				</view>
				<view class="address-right">
					<view class="address-info">
						<view class="address-info-top">
							{{ order.address_detail || '' }}
						</view>
						<view class="address-info-bottom">
							<text class="address-name">{{ order.address_nickname || ''}}</text>
							<text class="address-phone">-{{ order.address_phone || ''}}</text>
						</view>
					</view>
<!--					<view class="address-righticon">-->
<!--						<image src="/static/icon/right.png"></image>-->
<!--					</view>-->
				</view>
			</view>
			<!-- 商品信息 -->
			<view class="goods" v-for="item in items" @click="toGoodsDetail(item.product_id)">
				<view class="goods-left">
					<image :src="item.product.post_url"></image>
				</view>
				<view class="goods-center">
					<text class="goods-name">{{ item.product.title || '' }}</text>
<!--					<text class="goods-spec">规格：1kg/份</text>-->
					<text class="goods-num">数量：{{ item.count || 0 }} {{ item.product.unit || '' }}</text>
				</view>
				<view class="goods-right">
					￥<text class="goods-price">38.8</text>
				</view>
			</view>
			<!-- 价格信息 -->
			<view class="price">
				<view class="price-top">
					<view class="price-top-xiaoji" v-if="order.discount_amount">
						<text class="price-top-left">商品小计</text>
						<view class="price-top-right">
							￥<text class="xiaoji-price">{{ order.amount }}</text>
						</view>
					</view>
					<view class="price-top-youhui" v-if="order.discount_amount">
						<text class="price-top-left">优惠</text>
						<text class="youhui-price">-￥{{ order.discount_amount }}</text>
					</view>
				</view>
				<view class="price-bottom">
					<text class="price-bottom-left">应付金额合计</text>
					<view class="price-bottom-right">
						￥<text class="xiaoji-price">{{ order.payment_amount }}</text>
					</view>
				</view>
			</view>
			<!-- 订单信息 -->
			<view class="order">
				<view class="order-item">
					<text class="order-item-left">下单时间</text>
					<text class="order-item-right">{{ order.create_time }}</text>
				</view>
				<view class="order-item">
					<text class="order-item-left">订单编号</text>
					<text class="order-item-right">{{ order.order_no }}</text>
				</view>
				<view class="order-item">
					<text class="order-item-left">支付方式</text>
					<text class="order-item-right">微信</text>
				</view>
				<view class="order-item" v-if="order.transaction_id">
					<text class="order-item-left">交易流水号</text>
					<text class="order-item-right">{{ order.transaction_id || '' }}</text>
				</view>
			</view>
		</view>

		<!-- 底部栏 -->
		<view class="bottom">
			<view class="btns">
				<button class="cancel" v-if="order.statusText=='待支付' || order.statusText=='已支付'"
					@click="cancelOrder()">取消订单</button>
<!--				<button class="cancel" v-if="order.statusText=='待收货' || order.statusText=='待评价'">再来一单</button>-->
				<button class="pay" v-if="order.statusText=='待支付'" @click="payment(order.id)">支付</button>
				<button class="pay" v-if="order.statusText=='已支付'" @click="remind()">提醒发货</button>
				<button class="pay" v-if="order.statusText=='待收货'">确认收货</button>
        <button class="cancel" v-if="order.statusText=='已支付'" @click="refund(order.id)">退款/售后</button>
<!--				<button class="cancel" v-if="order.statusText!=='待支付' && order.statusText!=='退款中'&& order.statusText!=='已取消'" @click="refund(order.id)">退款/售后</button>-->
				<button class="pay" v-if="order.statusText=='待评价' && !order.comments" @click="goComment()">去评价</button>
			</view>
		</view>


    <!-- 退款弹窗 -->
    <u-popup v-model="showRefundPopup" mode="bottom" border-radius="16">
      <view class="refund-popup">
        <view class="popup-title">申请退款</view>
        <view class="refund-form">
          <view class="form-item">
            <view class="form-label">退款原因</view>
            <textarea class="refund-remark" v-model="refundReason" placeholder="请输入退款说明（选填）" maxlength="200"></textarea>
            <view class="char-count">{{ refundReason.length }}/200</view>
          </view>
        </view>
        <view class="popup-buttons" style="padding-bottom: 20rpx">
          <button class="popup-btn cancel" @click="showRefundPopup = false">取消</button>
          <button class="popup-btn confirm" @click="submitRefund">确认退款</button>
        </view>
      </view>
    </u-popup>
	</view>
</template>

<script>
  import { ORDER_STATUS, ORDER_STATUS_TEXT, ORDER_STATUS_ICON } from "../../utils/enum";
  import dayjs from "dayjs";
  export default {
		data() {
			return {
				order: {
					status: "待支付"
				},
        ORDER_STATUS,
        ORDER_STATUS_TEXT,
        ORDER_STATUS_ICON,
        expreTime: 0,
        items: [],
        interval: null,

        showRefundPopup: false,
        refundOrderId: '',
        refundReason: '',
			}
		},
    onLoad({ orderId }) {
      if (!this.$store.state.userInfo.id) {
        return
      }
      this.$api.getOrderDetail(orderId).then(res => {
        let _res = res || {}
        this.order = {
          ..._res,
          statusText: ORDER_STATUS_TEXT[_res.status],
          comments: _res.comments ? _res.comments.length : 0
        }
        if (this.order.status === ORDER_STATUS.PENDING && this.order.time_expire) {
          this.interval = setInterval(() => {
            this.getExpireTime()
          },1000)
        }
        if (this.order.items && this.order.items.length) {
          this.items = this.order.items.map(item => {
            let cartItem = {}
            if (item.product_detail) {
              cartItem = JSON.parse(item.product_detail)
            }
            return {
              ...cartItem,
            }
          }).filter(item => item.id)
        }

        console.log(this.order)
      })
    },
		methods: {
      // 计算订单自动关闭时间与现在差多久
      getExpireTime() {
        // this.order.time_expire 是年月日 时分秒，使用dayjs判断多分钟后过期
        this.expreTime = dayjs(this.order.time_expire).diff(dayjs(), 'minute')
        if (this.expreTime <= 0) {
          this.$api.cancelOrder({ id: this.order.id })
          clearInterval(this.interval)
          // 退出
          uni.reLaunch({
            url: '/pages/order/order'
          })
        }
      },
      toGoodsDetail(id) {
        uni.navigateTo({
          url: "/pages/goods/goods?id=" + id
        })
      },
			// 跳转去评价页面
			goComment() {
				uni.navigateTo({
					url: "/pages/order/comment?orderId=" + this.order.id
				})
			},
      // 退款
      refund(orderId) {
        if (!orderId) {
          this.$utils.toastTip("订单ID不能为空");
          return;
        }
        this.showRefundPopup = true
        this.refundOrderId = orderId
      },
      submitRefund() {
        if (!this.refundReason) {
          this.$utils.toastTip("退款原因不能为空");
          return;
        }
        this.$api.refundOrder({
          id: this.refundOrderId,
          refund_reason: this.refundReason,
        }).then(res => {
          this.$utils.toastTip("退款申请提交成功");
          this.showRefundPopup = false
          // 返回订单
          uni.redirectTo({
            url: "/pages/order/order"
          })
        })
      },

      payment(order_id){
        uni.showLoading({
          title:'微信支付请求'
        });
        const that = this
        this.$api.createPay({
          order_id
        }).then(payment =>{
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: payment.timestamp,
            nonceStr: payment.nonce_str,
            package: payment.package,
            signType: payment.signType,
            paySign: payment.paySign,
            success:(result)=> {
              uni.showToast({
                title:'支付成功'
              });
            },
            fail: (result) => {
              uni.showToast({
                icon:'none',
                title:'支付失败',
              });
            },
            complete: () => {
              setTimeout(() => {
                uni.navigateTo({
                  url: "/pages/cart/paymentinfo?orderId=" + order_id
                })
              }, 1000);
            }
          });
        }).catch(res=>{
          this.loading = false;
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/cart/paymentinfo?orderId=" + order_id
            })
          }, 1000);
        })
      },
			// 提醒发货
			remind() {
				this.$utils.toastTip("已向商家发送发货提醒");
			},
			// 取消订单
			cancelOrder() {
				this.$utils.showConfirm("确定要取消订单吗？").then(res => {
					if (res.confirm) {
            // 调用取消订单API
            uni.showLoading({
              title: '取消中...'
            })
            this.$api.cancelOrder({
              id: this.order.id
            }).then(res => {
              this.$utils.toastTip("取消成功！");
              this.order.status = ORDER_STATUS.CANCELLED
              this.order.statusText = ORDER_STATUS_TEXT[ORDER_STATUS.CANCELLED]
            })
					}
				});

			}
		}
	}
</script>

<style>
	page {
		background: #F8F9FA;
	}
</style>

<style lang="scss" scoped>
	.header {
		border-bottom-left-radius: 60% 15%;
		border-bottom-right-radius: 60% 15%;
		background: linear-gradient(#40AE36, #7AC158);
		color: #FEFFFE;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 50rpx 0rpx;


		.header-title {
			display: flex;
			align-items: center;

			.header-icon {
				image {
					width: 80rpx;
					height: 80rpx;
				}
			}

			.header-status {
				font-size: 36rpx;
				margin-left: 16rpx;
			}
		}

		.header-content {
			margin-top: 16rpx;
		}

		.header-empty {
			padding-bottom: 100rpx;
		}

	}

	.content {
		margin: 0rpx 30rpx;

		.address {
			display: flex;
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 32rpx 20rpx;
			margin-top: -100rpx;

			.address-left {

				image {
					width: 48rpx;
					height: 48rpx;
				}
			}

			.address-right {
				display: flex;
				align-items: center;

				.address-info {
					display: flex;
					flex-direction: column;
					padding: 0rpx 40rpx 0rpx 20rpx;

					.address-info-top {
						font-size: 30rpx;
						font-weight: 600;
						color: #333333;
					}

					.address-info-bottom {
						font-size: 24rpx;
						color: #999999;
						margin-top: 6rpx;
					}
				}

				.address-righticon {

					image {
						width: 48rpx;
						height: 48rpx;
					}
				}
			}
		}

		.goods {
			display: flex;
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 32rpx 30rpx;
			margin-top: 22rpx;

			.goods-left {

				image {
					width: 130rpx;
					height: 130rpx;
				}
			}

			.goods-center {
        flex-grow: 1;
				display: flex;
				flex-direction: column;
				padding: 0rpx 60rpx 0rpx 30rpx;

				.goods-name {
					font-size: 26rpx;
					font-weight: 600;
					color: #333333;
				}

				.goods-spec {
					font-size: 22rpx;
					color: #999999;
					margin-top: 10rpx;
				}

				.goods-num {
					font-size: 22rpx;
					color: #999999;
				}
			}

			.goods-right {
				font-size: 22rpx;
				font-weight: 600;

				.goods-price {
					font-size: 32rpx;
					color: #333333;
				}
			}

		}

		.price {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 32rpx 30rpx;
			margin-top: 22rpx;

			.price-top {
				display: flex;
				flex-direction: column;
				line-height: 40rpx;
				padding: 10rpx 0rpx;
				border-bottom: 1rpx solid #ECECEC;

				.price-top-left {
					font-size: 24rpx;
					color: #666666;
				}

				.price-top-xiaoji {
					display: flex;
					justify-content: space-between;

					.price-top-right {
						font-weight: 600;
						font-size: 22rpx;

						.xiaoji-price {
							font-size: 32rpx;
						}
					}

				}

				.price-top-youhui {
					display: flex;
					justify-content: space-between;

					.youhui-price {
						font-size: 24rpx;
						color: #333333;
					}
				}
			}

			.price-bottom {
				margin-top: 16rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.price-bottom-left {
					font-size: 24rpx;
					font-weight: 600;
					color: #333333;
				}

				.price-bottom-right {
					font-weight: 600;
					font-size: 22rpx;
					color: #F55726;

					.xiaoji-price {
						font-size: 32rpx;
					}
				}
			}
		}

		.order {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 32rpx 30rpx;
			margin-top: 22rpx;

			.order-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				line-height: 50rpx;

				.order-item-left {
					font-size: 24rpx;
					color: #999999;
				}

				.order-item-right {
					font-size: 24rpx;
					color: #333333;
				}
			}
		}
	}

	.bottom {
		position: fixed;
		bottom: var(--window-bottom, 0);
		width: 100%;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 22rpx 0rpx;
    padding-bottom: 60rpx;

	}

	.btns {
		display: flex;
		margin-right: 30rpx;

		button {
			border-radius: 24rpx;
			background-color: #FFFFFF;
			margin: 0;
		}
    button+button {
      margin-right: 20rpx;
    }

		button::after {
			border: none;
		}

		.cancel {
			font-size: 24rpx;
			color: #333333;
			border: 1rpx solid #999999;
			margin-right: 20rpx;
		}

		.pay {
			font-size: 24rpx;
			color: #40AE36;
			border: 1rpx solid #40AE36;
		}
	}

  /* 退款弹窗 */
  .refund-popup {
    padding: 30rpx;
  }

  .popup-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .refund-form {
    margin-bottom: 30rpx;
  }

  .form-item {
    margin-bottom: 20rpx;
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
  }

  .refund-remark {
    width: 100%;
    height: 200rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
  }

  .char-count {
    text-align: right;
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }

  .popup-buttons {
    display: flex;
    justify-content: space-between;
  }

  .popup-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 40rpx;
    font-size: 28rpx;
    margin: 0 10rpx;
  }

  .popup-btn.cancel {
    background-color: #f5f5f5;
    color: #666;
  }

  .popup-btn.confirm {
    background-color: #40AE36;
    color: #fff;
  }
</style>
